package cn.yitun.chat.yitunservermanagecore.general.manage.generator.controller;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.annotation.Log;
import cn.yitun.chat.yitunservercommonlib.crud.yitun.BaseController;
import cn.yitun.chat.yitunservercommonlib.crud.yitun.BaseDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.common.GeneratorInfo;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunservermanagecore.general.manage.generator.service.GeneratorService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RequestMapping("/common/generator")
@RestController
public class GeneratorController extends BaseController {

	@Autowired
	private GeneratorService generatorService;

	@GetMapping("/list")
	List<Map<String, Object>> list() {
		List<Map<String, Object>> list = generatorService.list();
		return list;
	}

	@PostMapping("/page")
	ResultMessage list(@RequestBody BaseDto baseDto) {
		PageHelper.startPage(baseDto.getCurrentPageNo() , baseDto.getPageSize());
		List<Map<String, Object>> list = generatorService.list();
		return new ResultMessage(R.param("page", new PageInfo<>( list)));
	}

	@Log(value = "代码生成" , storeParams = false)
	@PostMapping("/code/{tableName}")
	public void code(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("tableName") String tableName) throws IOException {
        List<String> tableNames = new ArrayList<>();
        tableNames.add(tableName);
		byte[] data = generatorService.generatorCode(tableNames);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"yitun.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		response.setHeader("Access-Control-Allow-Origin" , "*");
		IOUtils.write(data, response.getOutputStream());
	}

	@Log(value = "批量代码生成" , storeParams = false)
	@PostMapping("/batchCode")
	public void batchCode(HttpServletRequest request, HttpServletResponse response,@RequestBody String tables) throws IOException {
		List<String> tableNames = new ArrayList<>();
        JsonElement jsonElement = new JsonParser().parse(tables);
        JsonObject tablesJson = jsonElement.getAsJsonObject();
		if (!tablesJson.has("tables") )
			throw new YitunException(ExceptionEnum.LOSE_FILED);
		JsonArray array = tablesJson.getAsJsonArray("tables");
		if (array == null && array.size() == 0 )
			return ;
		Iterator<JsonElement> it = array.iterator();
		String table = "";
		while (it.hasNext()) {
            table = it.next().getAsString();
            if (YitunStringUtil.isNotEmpty(table)) {
                tableNames.add(table);
            }
        }
		byte[] data = generatorService.generatorCode(tableNames);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"yitun.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		//zuul环境下，可能会引发多次cors检测同源限制问题
		response.setHeader("Access-Control-Allow-Origin" , "*");
		IOUtils.write(data, response.getOutputStream());
	}

	@Log("代码生成参数编辑")
	@PostMapping("/update")
	ResultMessage update(@RequestBody GeneratorInfo generatorInfo) {
		if (YitunStringUtil.isEmpty(generatorInfo.getPack()) || YitunStringUtil.isEmpty(generatorInfo.getAuthor())
				|| YitunStringUtil.isEmpty(generatorInfo.getEmail()) || YitunStringUtil.isEmpty(generatorInfo.getDataEntityPath()) )
			throw new YitunException(ExceptionEnum.LOSE_FILED);
		generatorService.updateGeneParam(generatorInfo);
		return new ResultMessage();
	}

	@GetMapping("/generatorParams")
	ResultMessage generatorParams() {
		return new ResultMessage(R.param("data", generatorService.getGeneParam("0")));
	}
}
